package com.chiasma.writogether.client;

import java.util.List;

import com.chiasma.writogether.model.Entries;
import com.chiasma.writogether.rpc.LocalUserService;
import com.chiasma.writogether.rpc.LocalUserServiceAsync;
import com.chiasma.writogether.rpc.WritogetherService;
import com.chiasma.writogether.rpc.WritogetherServiceAsync;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.layout.client.Layout;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.LayoutPanel;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.ToggleButton;
import com.google.gwt.user.client.ui.VerticalPanel;

public class Writogether implements EntryPoint {
	
	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	private WritogetherServiceAsync writogetherService;
	private LocalUserServiceAsync userService;
	
	
	private ScrollPanel historyPanel = new ScrollPanel();
	private LayoutPanel entryPanel = new LayoutPanel(); 
	
	private TextArea contentTextbox = new TextArea();

	private String currentUser = "";
	private LayoutPanel userProfilePanel = new LayoutPanel();
	
	private DockLayoutPanel mainLayout = new DockLayoutPanel(Unit.EM);
	private LayoutPanel vSplit = new LayoutPanel();
	private LayoutPanel toggleBarLayout = new LayoutPanel();
	private VerticalPanel htmlFooterLayout = new VerticalPanel();
	
	private final String contentTextboxDefault = "Continue the story here...."; 
	
	public Writogether(){
		writogetherService = GWT.create(WritogetherService.class);
		userService = GWT.create(LocalUserService.class);
	}
	
	public void onModuleLoad() {
		
		refreshHistoryPanel();
		getUserProfile();
	
		//FlexTable layoutTable = new FlexTable();
		FlexTable footerTable = new FlexTable();
	    footerTable.setWidth("100%");

		contentTextbox.setWidth("600px");
		contentTextbox.setText(contentTextboxDefault);
		contentTextbox.addFocusHandler(new FocusHandler(){

			public void onFocus(FocusEvent event) {
				if (contentTextbox.getText().equalsIgnoreCase(contentTextboxDefault))
					contentTextbox.setText("");
			}
			
		});
		footerTable.setWidget(0,0,contentTextbox);
		
		
		final Button submitButton = new Button("Submit Entry");
		submitButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				try {
					
					//lock the button when it is posting the content
					submitButton.setEnabled(false);
					submitButton.setText("Posting Entries...Please Wait");
					writogetherService.createNewEntries(currentUser, contentTextbox.getText(), new AsyncCallback<Boolean>() {
							
						public void onFailure(Throwable caught) {
							Window.alert("Cannot Submit new Entries");
							submitButton.setEnabled(true);
							submitButton.setText("Retry Again ?");
							
						}
						public void onSuccess(Boolean result) {
							refreshHistoryPanel();
							submitButton.setEnabled(true);
							submitButton.setText("Submit Entry");
							contentTextbox.setText("");
						}
					});
					
				}catch(Exception ex) {}
			}
			
		});
		footerTable.setWidget(1,0,submitButton);
		
		
		final Timer t = new Timer(){
  	        public void run() {
  	        	refreshHistoryPanel();
  	        }
  	    };
	    
  	    
  	    
	    final ToggleButton toggleButton = new ToggleButton("Auto-Refresh is currently Off", "Auto-Refresh is currently On");
	    
	    toggleButton.addClickHandler(new ClickHandler() {
	      public void onClick(ClickEvent event) {
	        if (toggleButton.isDown()) {
	        	t.scheduleRepeating(1000*60);
	        } else {
	          t.cancel();
	        }
	      }
	    });
	    
	    HTML footerHTML = new HTML("writogether is a collaborative writing concept and it is under beta testing.");
	    Image footerImage = new Image("http://code.google.com/appengine/images/appengine-silver-120x30.gif");

	    
	    
		//entryPanel.add(layoutTable);
		
		vSplit.add(historyPanel); 
		//vSplit.add(entryPanel);

		vSplit.setWidgetTopHeight(historyPanel, 0, Unit.PCT, 60, Unit.PCT);
		//vSplit.setWidgetBottomHeight(entryPanel, 0, Unit.PCT, 20, Unit.PCT); 
		
		
	    
	    
	    footerTable.setWidget(2, 0, footerHTML);
	    footerTable.setWidget(3, 0, footerImage);
	    footerTable.setWidget(4, 0, toggleButton);
	    footerTable.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER);
	    footerTable.getFlexCellFormatter().setHorizontalAlignment(1, 0, HasHorizontalAlignment.ALIGN_CENTER);
	    footerTable.getFlexCellFormatter().setHorizontalAlignment(2, 0, HasHorizontalAlignment.ALIGN_CENTER);
	    footerTable.getFlexCellFormatter().setHorizontalAlignment(3, 0, HasHorizontalAlignment.ALIGN_CENTER);
	    footerTable.getFlexCellFormatter().setHorizontalAlignment(4, 0, HasHorizontalAlignment.ALIGN_CENTER);
	    
	    mainLayout.addNorth(userProfilePanel, 3);
	    mainLayout.add(vSplit);
	    mainLayout.addSouth(footerTable, 14);
	    
	    
	    RootLayoutPanel rp = RootLayoutPanel.get();
	    rp.add(mainLayout);
	   
	}
	
	
	private void getUserProfile(){
		try{

			userService.getCurrentLoginUserNickname(new AsyncCallback<String>(){
				public void onFailure(Throwable caught) {
					//Window.alert(caught.toString());
					//Window.alert("Problems getting the current user");
					getUserProfile();
				}

				public void onSuccess(String result) {
					currentUser = result;
				}
				
			});
			final HTML logoutLink = new HTML();
			userService.getLogoutUrl(new AsyncCallback<String>(){

				public void onFailure(Throwable caught) {
					//Window.alert("Problems getting the logout url");
				}

				public void onSuccess(String result) {
					logoutLink.setHTML(currentUser+" | <a href="+result+">Sign Out</a>");
				}
				
			});
			userProfilePanel.add(logoutLink);
			//userProfilePanel.setWidgetHorizontalPosition(logoutLink, Layout.Alignment.valueOf("center"));
			
			
		}catch(Exception ex){
			Window.alert("Exception?");
			
		}
		
	}
	private void refreshHistoryPanel() {

		historyPanel.clear();
		try {
			writogetherService.getAllEntries(new AsyncCallback<List<Entries>>() {
				FlexTable entryTable = new FlexTable();
				public void onFailure(Throwable caught) {
					//Window.alert(caught.toString());
					entryTable.setWidget(0,0,new HTML("Problems connecting to the DataStore"));
					historyPanel.add(entryTable);
				}
				
				public void onSuccess(List<Entries> entriesList) {
					
					if (entriesList.size() > 0) {
						
						for(int i=0; i<entriesList.size(); i++){
							entryTable.setWidget(i,0, new HTML(entriesList.get(i).getEntryContent()));
							
							if (currentUser.equalsIgnoreCase("karlili.li"))	{
								entryTable.setWidget(i,1, new HTML(entriesList.get(i).getWriterName()));
							}else{
								entryTable.setWidget(i,1, new HTML(""));
							}
							entryTable.getFlexCellFormatter().setWidth(i, 0, "90%");
							entryTable.getFlexCellFormatter().setWidth(i, 1, "");
							entryTable.getFlexCellFormatter().setAlignment(i,1, HasHorizontalAlignment.ALIGN_RIGHT, HasVerticalAlignment.ALIGN_TOP);
							
						}
						
						
						
					}else {
						entryTable.setWidget(0,0, new HTML("No Entry is Found in Datastore"));
					}
					historyPanel.add(entryTable);
					historyPanel.scrollToBottom();
					
					
				}
			
			});
			
		}catch(Exception e) {}
	
	}
}
